package movee.netconf.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@SpringBootApplication
public class NetconfClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(NetconfClientApplication.class, args);
    }

    @Bean
    public CommandLineRunner runner() {
        return (args) -> {
            // netconfTest();
        };
    }

    private void netconfTest() throws Exception {

        // 厂商支持的netconf能力
        List<String> capabilities = new ArrayList<>();
        capabilities.addAll(NetconfConstants.DEFAULT_CLIENT_CAPABILITIES);
        capabilities.add(NetconfConstants.HUAWEI_CAPABILITY_ACTION_1_0);
        capabilities.add(NetconfConstants.HUAWEI_CAPABILITY_EXCHANGE_1_0);

        // 连接netconf
        Device device = createDevice(capabilities);
        device.connect();

        String rpc = "<?xml version='1.0' encoding='UTF-8'?>\n" +
                "<rpc message-id=\"100\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
                "  <get>\n" +
                "    <filter type=\"subtree\">\n" +
                "      <system xmlns=\"http://www.huawei.com/netconf/vrp\" content-version=\"1.0\" format-version=\"1.0\">\n" +
                "  <systemInfo>\n" +
                "    <sysName/>\n" +
                "  </systemInfo>" +
                "</system>" +
                "    </filter>\n" +
                "  </get>\n" +
                "</rpc>]]>]]>";

        // 发送请求，获取响应
        XML rpc_reply = device.executeRPC(rpc);
        log.info("val1: {}", rpc_reply.findValue(Arrays.asList("sysName")));

        // 关闭
        device.close();
    }

    public Device createDevice(List<String> capabilities) throws NetconfException {
        return Device.builder()
                .hostName("192.168.238.226")
                .port(22)
                .userName("trust")
                .password("Trust@123")
                .strictHostKeyChecking(false)
                .netconfCapabilities(capabilities)
                .build();
    }

}
